# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '54': {  # 聚宝盆 支付宝红包/扫码/H5 2.5% 100-10000 宝转卡 1.8% 10-50000 dwc
        'API_KEY': 'FXIT^7R98*UMn#jN',
        'alipay_gateway': 'https://api.jbp-pay.com/apply/Deposit',
        'query_gateway': 'https://api.jbp-pay.com/Query/OrderInquiry',
    },
    '55': {  # 聚宝盆 支付宝红包/扫码/H5 2.5% 100-10000 宝转卡 1.8% 10-50000 witch
        'API_KEY': 'q6VVw#ZkN&TptdIv',
        'alipay_gateway': 'https://api.jbp-pay.com/apply/Deposit',
        'query_gateway': 'https://api.jbp-pay.com/Query/OrderInquiry',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_alipay_gateway(mch_id):
    return APP_CONF[mch_id]['alipay_gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(d, key):
    s = '{}{}{}{}{}{}{}{}{}{}{}{}{}'.format(
        key, d['company_id'], d['bank_id'], d['amount'], d['company_order_num'], d['company_user'],
        d['estimated_payment_bank'], d['deposit_mode'], d['group_id'], d['web_url'], d['memo'], d['note'],
        d['note_model']
    )
    return _gen_sign(s)


def generate_create_rsp_sign(d, key):
    s = '{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}'.format(
        key, d['bank_card_num'], d['bank_acc_name'], '%.2f' % d['amount'], d['email'], d['company_order_num'],
        d['datetime'], d['note'], d['mownecum_order_num'], d['status'], d['error_msg'], d['mode'],
        d['issuing_bank_address'], d['break_url'], d['deposit_mode'], d['collection_bank_id']
    )
    return _gen_sign(s)


def generate_verify_sign(d, key):
    s = '{}{}{}{}{}{}{}{}{}'.format(
        key, d['pay_time'], d['bank_id'], '%.2f' % float(d['amount']), d['company_order_num'], d['mownecum_order_num'],
        d['fee'], d['transaction_charge'], d['deposit_mode']
    )
    return _gen_sign(s)


def generate_query_sign(d, key):
    s = '{}{}{}{}{}'.format(
        key, d['company_id'], d['company_order_num'], d['mownecum_order_num'], '%.2f' % float(d['amount'])
    )
    return _gen_sign(s)


def generate_query_rsp_sign(d, key):
    s = '{}{}{}{}{}{}{}'.format(
        key, d['mownecum_order_num'], d['company_order_num'], d['status'], '%.2f' % float(d['amount']),
                                                                           '%.2f' % float(
                                                                               d['exact_transaction_charge']),
        d['transaction_type']
    )
    return _gen_sign(s)


def verify_create_rsp_sign(params, key):
    sign = params['key']
    calculated_sign = generate_create_rsp_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("jubaopenpay create rsp sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('create rsp sign not pass, data: %s' % params)


def verify_notify_sign(params, key):
    sign = params['key']
    calculated_sign = generate_verify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("jubaopenpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('verify sign not pass, data: %s' % params)


def verify_query_rsp_sign(params, key):
    sign = params['key']
    calculated_sign = generate_query_rsp_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("jubaopenpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('querr rsp sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return '30'
    return '30'


def _get_deposit_mode(service):
    if service == 'wap':
        return '4'
    return '2'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('company_id', app_id),
        ('bank_id', _get_pay_type(service)),
        ('amount', '%.2f' % pay_amount),
        ('company_order_num', str(pay.id)),
        ('company_user', str(pay.user_id)),
        ('estimated_payment_bank', _get_pay_type(service)),
        ('deposit_mode', _get_deposit_mode(service)),
        ('group_id', '0'),
        ('web_url', 'www.iiittt.com'),
        ('memo', 'charge'),
        ('note', 'charge'),
        ('note_model', ''),
        ('terminal', '2'),  # 使用终端：1电脑端2手机端3平板9其他
    ))
    parameter_dict['key'] = generate_sign(parameter_dict, _gen_sign(api_key))
    _LOGGER.info("jubaopenpay create: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['company_order_num'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_alipay_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('jubaopenpay create rsp, %s', response.text)
    create_rsp_data = json.loads(response.text)
    verify_create_rsp_sign(create_rsp_data, _gen_sign(api_key))
    return {'charge_info': json.loads(response.text)['break_url']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("jubaopenpay notify data: %s", data)
    verify_notify_sign(data, _gen_sign(api_key))
    pay_id = data['company_order_num']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('jubaopenpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = ''
    trade_no = str(data['mownecum_order_num'])
    total_fee = float(data['amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 1 交易成功
    if trade_no and total_fee > 0.0:
        _LOGGER.info('jubaopenpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('company_id', app_id),
        ('company_order_num', str(pay_order.id)),
        ('mownecum_order_num', str(pay_order.third_id)),
        ('amount', '%.2f' % float(pay_order.total_fee)),
    ))
    parameter_dict['key'] = generate_query_sign(parameter_dict, _gen_sign(api_key))
    _LOGGER.info('jubaopenpay query data, %s', json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('jubaopenpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        verify_query_rsp_sign(data, _gen_sign(api_key))
        mch_id = pay_order.mch_id
        trade_status = str(data['status'])
        total_fee = float(data['amount'])
        trade_no = data['mownecum_order_num']
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # 状态：1处理成功-success，0处理失败-failed，3处理中pending
        if trade_status == '1':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('jubaopenpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
